import { Inject, Injectable, NestMiddleware } from '@nestjs/common';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { NextFunction } from 'express';
import { getClientIp } from '../../utils/ip.utils';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  // 注入日志相关依赖
  constructor(
    @Inject(WINSTON_MODULE_NEST_PROVIDER)
    private readonly logger: Logger,
  ) {}

  use(req: Request, res: Response, next: NextFunction) {
    this.logger.log(
      'info',
      `ip:【${getClientIp(req)}】,访问:【${req.url}】, 请求方法: 【${
        req.method
      }】`,
    );
    next();
  }
}
